import {ref,onMounted,computed} from 'vue'
import {useRoute,useRouter} from 'vue-router'
import type {Ref} from 'vue'
import type { UserListType } from '@/typings/ladyType'
import { getUsersApi } from '@/api/ladyApi'
import { objToQuery } from '@/utils/ladytools'
type userListType =[
    Ref<number>,
    Ref<UserListType[]>,
    Ref<number>,
    (page:number)=>Promise<void>
]
const useUserList=():userListType=>{
    const router = useRouter()
    const route = useRoute()
    const data=ref<UserListType[]>([])
    const total=ref(0)
    const currentPage = computed(()=>{
        return route.query.page? +route.query.page:1
    })
    const loadData = async (page: number, search?: Record<string, string> | undefined) => {
        let query = ''
        if (typeof search != 'undefined') {
          query = objToQuery(search)
        }
        router.replace(`?page=${page}${query}`)
        // let ret=await getUsersApi(currentPage.value,query)
    //相比于老师的代码做了这里的修改,老师的代码是上面的，也就是将老师的currentPage存在异步因此页码更新可能不及时，这里使用Page
        let ret=await getUsersApi(page, query)
        if (ret.code === 0) {
            data.value = ret.data.users
            total.value = ret.data.total
        }
    }
    onMounted(()=>{
        loadData(currentPage.value)
    })
    return [currentPage,data,total,loadData]
}
export default useUserList